import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store'
import { h } from 'vue'
const Layout = () => import('@/views/Layout.vue')
const Home = () => import('@/views/home')
const TopCategory = () => import('@/views/category/index.vue')
const SubCategory = () => import('@/views/category/sub.vue')
const XtxGoodsPage = () => import('@/views/goods/index.vue')
const Login = () => import('@/views/login/index.vue')
const LoginCallback = () => import('@/views/login/components/callback.vue')
const Cart = () => import('@/views/cart/index.vue')
const PayCheckout = () => import('@/views/member/pay/checkout.vue')
const PayIndex = () => import('@/views/member/pay/index.vue')
const PayResult = () => import('@/views/member/pay/result.vue')
const MemberLayout = () => import('@/views/member/Layout.vue')
const MemberHome = () => import('@/views/member/home/index.vue')
const MemberOrder = () => import('@/views/member/order')
const MemberOrderDetail = () => import('@/views/member/order/detail.vue')
const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '/',
        component: Home
      },
      {
        path: '/category/:id',
        component: TopCategory
      },
      {
        path: '/category/sub/:id',
        component: SubCategory
      },
      {
        path: '/product/:id',
        component: XtxGoodsPage
      },
      {
        path: '/cart',
        component: Cart
      },
      {
        path: '/member/checkout',
        component: PayCheckout
      },
      {
        path: '/member/pay',
        component: PayIndex
      },
      {
        path: '/pay/callback',
        component: PayResult
      },
      {
        path: '/member',
        component: MemberLayout,
        children: [
          {
            path: '/member',
            component: MemberHome
          },
          {
            path: '/member/order',
            // 创建一个RouterView容易形成嵌套关系
            component: { render: () => h(<RouterView />) },
            children: [
              {
                path: '',
                component: MemberOrder
              },
              {
                path: ':id',
                component: MemberOrderDetail
              }
            ]
          }
        ]
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/login/callback',
    component: LoginCallback
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  scrollBehavior () {
    return { top: 0, left: 0 }
  },
  routes
})

// 设置前置守卫
router.beforeEach((to, from, next) => {
  const { profile } = store.state.user
  console.log(store)
  // 判断跳转结算页面的时候有没有登录,没有的话则跳转到登录页面
  if (!profile.token && to.path.startsWith('/member')) {
    return next('/login?redirectUrl=' + encodeURIComponent(to.fullPath))
  }
  next()
})

export default router
